package com.example.util;

import java.math.BigInteger;
import java.security.MessageDigest;

/**
 * 加密util
 * 
 * @author wangkai
 *
 * @date: 2019年5月31日 上午11:25:39
 */
public class EncryptionUtil {

	/**
	 * MD5加密
	 * 
	 * @param password
	 * @param salt
	 *            盐
	 * @return
	 */
	public static String encryptionMd5(String password, String salt) {
		StringBuffer newPassword = new StringBuffer(password);
		if (salt != null && salt.trim().length() > 0) {
			newPassword.append(salt);
		}
		try {
			MessageDigest md = MessageDigest.getInstance("MD5");
			md.update(newPassword.toString().getBytes());
			return new BigInteger(1, md.digest()).toString(16);
		} catch (Exception e) {
			throw new RuntimeException("md5加密错误");
		}
	}

	/**
	 * MD5加密
	 * 
	 * @param password
	 * @param salt
	 *            盐
	 * @param num
	 *            加密（md5(md5(''))）
	 * @return
	 */
	public static String encryptionMd5(String password, String salt, int num) {
		StringBuffer newPassword = new StringBuffer(password);
		if (salt != null && salt.trim().length() > 0) {
			newPassword.append(salt);
		}
		try {
			MessageDigest md = MessageDigest.getInstance("MD5");
			if (num == 1 || num == 0) {
				md.update(newPassword.toString().getBytes());
				return new BigInteger(1, md.digest()).toString(16);
			} else {
				String ps = newPassword.toString();
				for (int i = 0; i < num; i++) {
					if (i == 0) {
						md.update(ps.getBytes());
					} else {
						if (salt != null && salt.trim().length() > 0) {
							md.update(new String(ps + salt).getBytes());
						} else {
							md.update(new String(ps).getBytes());
						}
					}
					ps = new BigInteger(1, md.digest()).toString(16);
				}
				return ps;
			}
		} catch (Exception e) {
			throw new RuntimeException("md5加密错误");
		}
	}

}
